#!/usr/bin/python2.7
#coding=UTF-8
import os
import sys
import time
import os.path
import paramiko
from datetime import datetime
#ip=
#username=
#password=
#brand=""#品牌
nexus_user="admin"
nexus_pass="xxxx"
nexus_host="10.2.158.42"
nexus_port="8081"
nexus_repo="network"
wait_time=60

reload(sys)
sys.setdefaultencoding = 'utf-8'

backup_dir = "/home/ampdcp/nexus/network/backup"
dir_name = time.strftime('%Y%m', time.localtime())
upload_name = time.strftime('%Y%m%d%H%M%S', time.localtime())
local_path = backup_dir + '/' + ip

allbrand = [{
    'name': 'HUAWEI',
    'cmd': ['screen-length 0 temporary', 'display current-configuration']
}, {
    'name': 'H3C',
    'cmd': ['screen-length disable', 'display current-configuration']
}, {
    'name': 'CISCO',
    'cmd': ['ter len 0', 'show running-config']
}, {
    'name': 'ZTE',
    'cmd': ['enable', 'C9yd2018', 'ter len 0', 'show running-config']
}, {
    'name': 'MAIPU',
    'cmd': ['more off', 'show running-config']
}, {
    'name': 'RUIJIE',
    'cmd': ['ter len 0', 'show running-config']
}, {
    'name': 'FHN',
    'cmd': ['ter len 0', 'show running-config', ]
}, {
    'name': 'Juniper',
    'cmd': ['show configuration | no-more']
}, {
    'name': 'Radware',
    'cmd': ['/cfg/dump', 'n']
}, {
    'name': 'F5',
    'cmd': ['tmsh -q show running-config']
}, {
    'name': 'DIPU',
    'cmd': ['ter line 0','show run']
}]

def check_path():
  if not os.path.isdir(backup_dir):
      os.makedirs(backup_dir)
  return True

def get_backup_filename():
  if check_path():
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  try:
      ssh.connect(hostname = ip, username = username, password = password)
      ssh_shell = ssh.invoke_shell()
      time.sleep(int(wait_time))
      output = ssh_shell.recv(65535)
      if '>' in output:
          print ("login successfull")
      num = 0
      backup = open(local_path, "w")
      last_data_length=""
      for i in allbrand:
        if brand == i['name']:
          print(len(i['cmd']))
          for cmds in i['cmd']:
            ssh_shell.send(cmds + '\n')
            num = num + 1
            print(cmds)
            if len(i['cmd']) != num:
                backup.close()
                print("跳过本次循环")
                continue 
            time.sleep(1)
            backup = open(local_path, "a")
            while True:
                if ssh_shell.recv_ready():
                    recv = ssh_shell.recv(65535*10000000)
                    recv = recv.replace('\r', '')
                    recv_str = recv.decode('utf-8', 'ignore')
                    backup.write(recv)
                time.sleep(3)                
                #判断前一次获取的内容是否与本次内容完全相等
                if last_data_length == recv:
                    print ('----end----')
                    break
                else:
                    num=len(i['cmd'])
                last_data_length = recv
                print(len(recv))
            backup.close()
      ssh.close()
      return local_path
  except Exception as e:
      return False

def output(): 
    global file_privil
    global file_owner
    global file_group
    global file_name
    global upload_url
    file_privil = 664
    file_owner = 'shsnc'
    file_group = 'shsnc'
    file_name = local_path.split('/')[5]
    upload_full = file_name + '_' + upload_name
    upload_full_name = upload_full.replace('.','')
    upload_url = 'http://{}:{}/repository/{}/{}/{}'.format(nexus_host, nexus_port, nexus_repo, dir_name, upload_full_name)
    

def upload_backup_filename():
  cmd = 'curl -s -o /dev/null -w {} -u {}:"{}" --upload-file {} {}'.format('%{http_code}', nexus_user, nexus_pass, local_path, upload_url)
  return os.system(cmd)

if __name__ == "__main__":  
  check_path()
  get_backup_filename()
  out_result = output()
  upload_backup_filename()
  print(out_result)
  
sys.exit(0)